//
//  MessageCenterViewController.m
//  MobileOffice
//
//  Created by jjkj on 16/10/31.
//  Copyright © 2016年 liaoningjujin. All rights reserved.
//

#import "MessageCenterViewController.h"
#import "MessageCenterTableViewCell.h"
#import "AddressBookViewController.h"
#import "MessageCenterModel.h"
#import "PersonMessageViewController.h"

#define getMessageList @"getMessageList"
#define setMsgInfo @"setMsgInfo"
#define setDeleteMessageInfo @"setDeleteMessageInfo"//删除消息

@interface MessageCenterViewController ()<UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate,UIGestureRecognizerDelegate>
{
    UITableView *_tableView;//消息列表
    //UIButton * _grayButton;
    UIView * _searchView;//搜索框
    MessageCenterModel *_model;//消息列表
    UITableView *_searchTableView;//搜索结果列表
//    AddressSearchModel *_searchListModel;//搜索结果列表model
    UIView *_searchBackView;//搜索view
    UITapGestureRecognizer *_tapGesture;//手势
}
@property (nonatomic,strong) UISearchBar * searchBar;
@property (nonatomic,strong)UIView *deleteView;//删除框
@property (nonatomic,assign) NSInteger deleteRow;
@end

@implementation MessageCenterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setNavigationTitle:@"个人消息"];
    [self setRightBackNavigation];
    [self setLeftBackNavigation];
    [self creatView];
    [self messageListRequestWithName:@""];
    //增加监听，当键盘出现或改变时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    
    //增加监听，当键退出时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    // Do any additional setup after loading the view.
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    
}


- (void)keyboardWillShow:(NSNotification *)aNotification
{    
//    NSDictionary *userInfo = [aNotification userInfo];
//    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
//    CGRect keyboardRect = [aValue CGRectValue];
//    CGFloat height = keyboardRect.size.height;
    _tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapGestureClick)];
    
    [_tableView addGestureRecognizer:_tapGesture];
    // CGFloat width = keyboardRect.size.width;
    
}

- (void)tapGestureClick{
    [_searchBar resignFirstResponder];
}

#pragma mark -滚动视图delegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [_searchBar resignFirstResponder];
    if (self.deleteView) {
        [UIView animateWithDuration:0.2 animations:^{
            self.deleteView.y=IPHONE_HEIGHT;
        } completion:^(BOOL finished) {
            [self.deleteView removeFromSuperview];
            _tableView.height=IPHONE_HEIGHT-64-40;
            self.deleteView=nil;
        }];
    }
}

//当键退出时调用
- (void)keyboardWillHide:(NSNotification *)aNotification
{
    //    //获取键盘高度
    //    NSDictionary *userInfo = [aNotification userInfo];
    //    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    //    CGRect keyboardRect = [aValue CGRectValue];
    //    CGFloat height = keyboardRect.size.height;
    
//    [UIView animateWithDuration:0.3 animations:^{
//        _backMsgView.y=IPHONE_HEIGHT-51;
//    }];
    [_tableView removeGestureRecognizer:_tapGesture];
    //_tableView.y=64;
    
}

#pragma mark - creatTableView
- (void)creatView{
    //    if (_searchView) {
    //        //防止搜索按钮多次被点击
    //        return;
    //    }
    _pageNum=@"1";
    //    _grayButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 64, IPHONE_WIDTH, IPHONE_HEIGHT-64)];
    //    [_grayButton setBackgroundColor:COLOR(106, 107, 108, 0.7)];
    //    [_grayButton addTarget:self action:@selector(cancelSearch:) forControlEvents:UIControlEventTouchUpInside];
    //    [self.view addSubview:_grayButton];
    //搜索框
    _searchView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, IPHONE_WIDTH, 40)];
    _searchView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_searchView];
    //textField
    
    //searchBar
    
    _searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(1, 0, IPHONE_WIDTH-80, 40)];
    _searchBar.placeholder = @"请输入搜索内容";
    //_searchBar.showsSearchResultsButton=YES;
    //    _searchBar.borderStyle = UITextBorderStyleRoundedRect;
    //    _searchBar.font = FONT_14;
    //    _searchBar.clearButtonMode = UITextFieldViewModeWhileEditing;
    _searchBar.delegate = self;
    _searchBar.searchResultsButtonSelected=YES;
    _searchBar.searchBarStyle=UISearchBarStyleMinimal;
    _searchBar.returnKeyType = UIReturnKeyGo;
    
    [_searchView addSubview:_searchBar];
    //startSearchButton
    
    //搜索按钮
    UIButton * searchButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [searchButton setTitle:@"员工动态" forState:UIControlStateNormal];
    [searchButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    searchButton.backgroundColor=COLOR_SKYBLUE;
    searchButton.titleLabel.font = FONT_14;
    [_searchView addSubview:searchButton];
    //[searchButton setBackgroundColor:[UIColor yellowColor]];
    searchButton.frame = CGRectMake(_searchBar.x+_searchBar.width, _searchBar.y+5, IPHONE_WIDTH-(_searchBar.x+_searchBar.width)-8, 30);
    searchButton.layer.cornerRadius = 5;
    searchButton.layer.masksToBounds = YES;
    [searchButton addTarget:self action:@selector(addressClick) forControlEvents:UIControlEventTouchUpInside];
    
    _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 40, IPHONE_WIDTH, IPHONE_HEIGHT-64-40) style:UITableViewStylePlain];
    //_myTableView.backgroundColor=[UIColor redColor];
    _tableView.delegate=self;
    _tableView.dataSource=self;
    _tableView.tag=110;
    _tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    _tableView.showsVerticalScrollIndicator=NO;
    _tableView.showsHorizontalScrollIndicator=NO;
    [self addTableViewUpdateRefresh:_tableView BindingIdentity:@""];
    //    [self addTableViewLoadMoreData:_tableView BindingIdentity:@""];
    [self.view addSubview:_tableView];
    
    //    self.definesPresentationContext = YES;
}


#pragma mark -删除
- (void)creatViewDeleteView{
    if (self.deleteView) {
        return;
    }
    _tableView.height-=40;
    self.deleteView=[[UIView alloc]initWithFrame:CGRectMake(0, IPHONE_HEIGHT-64-40, IPHONE_WIDTH, 40)];
    [self.view addSubview:self.deleteView];
    
    UILabel *line1=[MyControl creatLabelWithFrame:CGRectMake(0, 0, IPHONE_WIDTH, 1) text:@""];
    line1.backgroundColor=BACKCOLOR_GRAY;
    [self.deleteView addSubview:line1];
    
    NSArray *title=@[@"全选",@"删除"];
    CGFloat buttonWidth=(IPHONE_WIDTH-(title.count+1)*10)/title.count;
    for (int i=0; i<title.count; i++) {
        UIButton *submitButton=[MyControl creatButtonWithFrame:CGRectMake(10*(i+1)+buttonWidth*i,1, buttonWidth, 39) target:self sel:@selector(deleteClick:) tag:120+i image:nil title:title[i]];
//        submitButton.layer.masksToBounds=YES;
//        submitButton.layer.cornerRadius=5;
//        [submitButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//        if (i==0) {
//            submitButton.backgroundColor=COLOR_MIDBLUE;
//        }else{
//            submitButton.backgroundColor=[UIColor orangeColor];
//        }
        if (i==0) {
            UILabel *line=[MyControl creatLabelWithFrame:CGRectMake(IPHONE_WIDTH/2, 10, 1, 20) text:@""];
            line.backgroundColor=BACKCOLOR_GRAY;
            [self.deleteView addSubview:line];
        }
        [self.deleteView addSubview:submitButton];
    }
}


#pragma mark - 删除点击

- (void)deleteClick:(UIButton *)button{
    if (button.tag==120) {
        [self setDeleteMessageInfoRequestWithType:@"0"];
    }else{
        //删除选中
        [self setDeleteMessageInfoRequestWithType:@"1"];
    }
    
    [_deleteView removeFromSuperview];
    _deleteView=nil;
    _tableView.height=IPHONE_HEIGHT-64-40;
}

#pragma mark - 通讯录
- (void)addressClick{
    AddressBookViewController *address=[AddressBookViewController new];
    [self.navigationController pushViewController:address animated:YES];
}



#pragma mark - TableViewDelagate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _model.dataArr.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *cellID=@"MessageCenterTableViewCell";
    MessageCenterTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellID];
    __weak MessageCenterViewController *mySelf=self;
    if (!cell) {
        cell=[[MessageCenterTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellID];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        cell.myBlock=^(NSInteger row){
            mySelf.deleteRow=row;
            [mySelf creatViewDeleteView];
        };
    }
    cell.row=indexPath.row;
    //取出数组中的model
    MessageCenterModel *model=_model.dataArr[indexPath.row];
    CGFloat messageHeight=[LZXHelper textHeightFromTextString:model.msgContent?model.msgContent:@"" width:cell.messageLabel.width fontSize:13]+2;
    cell.messageLabel.height=messageHeight;
    cell.timeLabel.y=cell.messageLabel.y+cell.messageLabel.height+8;
    cell.lineLabel.y=cell.timeLabel.y+cell.timeLabel.height+7;
    cell.height=messageHeight;
    [cell.headImageView setImageWithURL:[NSURL URLWithString:model.empIcon] placeholderImage:[UIImage imageNamed:@"k_portrait@2x"]];
    cell.nameLabel.text=model.empName?model.empName:@"";
    cell.msgTitleLabel.text=model.msgTitle?model.msgTitle:@"";
    cell.messageLabel.text=model.msgContent?model.msgContent:@"";
    cell.timeLabel.text=model.createTime?model.createTime:@"";
    //判断是否已读
    if ([model.isRead isEqualToString:@"0"]) {
        cell.nameLabel.textColor=[UIColor blackColor];
        cell.msgTitleLabel.textColor=[UIColor blackColor];
        cell.messageLabel.textColor=[UIColor blackColor];
        cell.timeLabel.textColor=[UIColor blackColor];
        cell.signLabel.hidden=NO;
    }else{
        cell.nameLabel.textColor=[UIColor grayColor];
        cell.msgTitleLabel.textColor=[UIColor grayColor];
        cell.messageLabel.textColor=[UIColor grayColor];
        cell.timeLabel.textColor=[UIColor grayColor];
        cell.signLabel.hidden=YES;
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    MessageCenterModel *model=_model.dataArr[indexPath.row];
    CGFloat messageHeight=[LZXHelper textHeightFromTextString:model.msgContent?model.msgContent:@"" width:IPHONE_WIDTH-71 fontSize:13]+2;
    return 72+messageHeight;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //跳转到消息详情列表
    MessageCenterModel *model=_model.dataArr[indexPath.row];
    PersonMessageViewController *person=[PersonMessageViewController new];
    person.receEmpName=[model.empName copy];
    person.receEmpId=[model.empId copy];
    [self.navigationController pushViewController:person animated:YES];
    if (![model.isRead isEqualToString:@"1"]) {
        [self messageSearchRequestWithID:model.empId];
    }
}

#pragma mark -下拉刷新
- (void)loadUpdateRefreshWithBindingIdentity:(NSString *)BindingIdentity{
    _pageNum=@"1";
    _isRefresh=YES;
    [self messageListRequestWithName:@""];
}

#pragma mark -searchBarDelegate

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    [searchBar resignFirstResponder];
    [self messageListRequestWithName:searchBar.text];
}

//手势响应  移除searchView
-(void)TwoTapGestureRecognizer:(UIGestureRecognizer*)gr{
    
    if (_searchBackView) {
        [_searchBackView removeFromSuperview];
        _searchBackView=nil;
    }
    
}

#pragma mark -通讯录列表请求

- (void)messageListRequestWithName:(NSString *)name{
    [LZXHelper postLoadViewWithText:HUD_PLEASEWAIT View:self.view];
    NSDictionary *dict=@{
                         @"msgName":name,
                         };
    
    //   字典转json
    NSData* jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
    NSString* str = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    //拼接soap字符串
    NSString* soap = [NSString stringWithFormat:@"<sessionId>%@</sessionId>\n<content>%@</content>",[LZXHelper getSessionID],str];
    // __weak AddressBookViewController *mySelf=self;
    [HttpRequest SOAPData:[LZXHelper getServerURL] SoapMthod:getMessageList soapBody:soap success:^(id responseObject) {
        [LZXHelper hideLoadViewWithView:self.view];
        
        //解析数据
        _model=[[MessageCenterModel alloc]initWithResponse:responseObject];
        if ([_model.code isEqualToString:@"200"]) {
            if (_isRefresh) {
                [self endRefreshWithTableView:_tableView];
            }
            if (_model.dataArr.count==0) {
                [self addReminderViewWithFrame:CGRectMake(0, (IPHONE_HEIGHT-64-40)/2, IPHONE_WIDTH, 20) msg:@"截止目前没有消息可查看~" backView:_tableView];
            }else{
                [self removeReminderView];
            }
            [_tableView reloadData];
        }else if([_model.code isEqualToString:@"220"]){
            [LZXHelper postMessageWithText:_model.msg View:self.view];
        }
    } failure:^(NSError *error) {
        [LZXHelper hideLoadViewWithView:self.view];
    }];
}
#pragma mark -设置为已读消息
- (void)messageSearchRequestWithID:(NSString *)personID{
    NSDictionary *dict=@{
                         @"msgId":personID,
                         };
    NSArray *selectArr=[NSArray arrayWithObject:dict];
    NSDictionary *selectDict=@{@"msgList":selectArr,
                               @"setOperate":@"0"};
    //   字典转json
    NSData* jsonData = [NSJSONSerialization dataWithJSONObject:selectDict options:NSJSONWritingPrettyPrinted error:nil];
    NSString* str = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    //拼接soap字符串
    NSString* soap = [NSString stringWithFormat:@"<sessionId>%@</sessionId>\n<content>%@</content>",[LZXHelper getSessionID],str];
    //[LZXHelper postLoadViewWithText:HUD_PLEASEWAIT View:self.view];
    // __weak AddressBookViewController *mySelf=self;
    [HttpRequest SOAPData:[LZXHelper getServerURL] SoapMthod:setMsgInfo soapBody:soap success:^(id responseObject) {
        //[LZXHelper hideLoadViewWithView:self.view];
        
        //解析数据
        BasicModel *model=[[BasicModel alloc]initWithResponse:responseObject];
        if ([model.code isEqualToString:@"200"]) {
            [self messageListRequestWithName:@""];
        }else if([model.code isEqualToString:@"220"]){
            [LZXHelper postMessageWithText:model.msg View:self.view];
        }
    } failure:^(NSError *error) {
        [LZXHelper hideLoadViewWithView:self.view];
    }];
}

#pragma mark -删除消息
- (void)setDeleteMessageInfoRequestWithType:(NSString *)type{
    NSMutableArray  *empIdArr=[NSMutableArray new];
    if ([type isEqualToString:@"0"]) {
        //删除全部
        
        for (MessageCenterModel *model in _model.dataArr) {
            [empIdArr addObject:model.empId];
            NSDictionary *dict=@{
                                 @"msgId":model.empId?model.empId:@"",
                                 };
            [empIdArr addObject:dict];
        }
    }else{
        //删除当前
        MessageCenterModel *model=_model.dataArr[self.deleteRow];
        NSDictionary *dict=@{
                             @"msgId":model.empId?model.empId:@"",
                             };
        [empIdArr addObject:dict];
    }
    NSDictionary *selectDict=@{@"msgList":empIdArr,
                               @"setOperate":@"3"};
    //   字典转json
    NSData* jsonData = [NSJSONSerialization dataWithJSONObject:selectDict options:NSJSONWritingPrettyPrinted error:nil];
    NSString* str = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    //拼接soap字符串
    NSString* soap = [NSString stringWithFormat:@"<sessionId>%@</sessionId>\n<content>%@</content>",[LZXHelper getSessionID],str];
    //[LZXHelper postLoadViewWithText:HUD_PLEASEWAIT View:self.view];
    // __weak AddressBookViewController *mySelf=self;
    [HttpRequest SOAPData:[LZXHelper getServerURL] SoapMthod:setMsgInfo soapBody:soap success:^(id responseObject) {
        //[LZXHelper hideLoadViewWithView:self.view];
        
        //解析数据
        BasicModel *model=[[BasicModel alloc]initWithResponse:responseObject];
        if ([model.code isEqualToString:@"220"]) {
            [self messageListRequestWithName:@""];
            [LZXHelper postMessageWithText:model.msg View:self.view];
        }else if([model.code isEqualToString:@"200"]){
            [LZXHelper postMessageWithText:model.msg View:self.view];
        }
    } failure:^(NSError *error) {
        [LZXHelper hideLoadViewWithView:self.view];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
